package com.ymy.boot.thread;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * {@link ScheduledExecutorService} 实现定时任务
 *
 * @author Ringo
 * @date 2021/10/23 22:13
 */
public class ScheduledExecutorServiceDemo {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        scheduleDemo(executorService);
    }

    // 定时任务
    public static void scheduleDemo(ScheduledExecutorService executorService) {
        executorService.schedule(() -> System.out.println("hello"), 3L, TimeUnit.SECONDS);
    }

    // 执行周期任务
    public static void scheduleAtFixedRateDemo(ScheduledExecutorService executorService) {
        executorService.scheduleAtFixedRate(
                () -> System.out.println(Thread.currentThread().getName() + "\thello"),
                3L, 2L, TimeUnit.SECONDS
        );
    }
}
